package com.newstart.springdatajpa.project.repository;

import com.newstart.springdatajpa.project.model.entity.Article;
import com.sun.xml.bind.v2.model.core.ID;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

public interface ArticleRepository extends JpaRepository<Article,Integer>, JpaSpecificationExecutor<Article> {

    @Transactional
    @Modifying(clearAutomatically = true)
    @Query(value = "update article set title='只更新标题,其他不动' where id=?1", nativeQuery = true)
    void updateById(int i);

    List<Article> findByTitleLike(String s);

    List<Article> findByTitleContainsOrContentContains(String title,String content);

    //from Article 相当于 select * from Article,?1代表第一个参数
    @Query(value = "from Article where content=?2 and title like %?1% ")
    List<Article> selectByTitleAndContent(String title, String content);

    //：占位符
    @Query(value = "from Article where id<:id and title like %:title% order by createTime desc")
    List<Article> selectByIdAndTitle(@Param("id") Integer id, @Param("title") String title);

    //实体类占位符
    @Query(value = "from Article a where a.id<= :#{#article.id} and a.title like %:#{#article.title}%")
    List<Article> selectByArticle(@Param("article") Article article,Pageable pageable);

    List<Article> findTop5ByContent(String content, Pageable pageable);

    @Query(value = "from Article a where a.projectId=?1 and a.content like ?2")
    List<Article> findTop5ByProjectIdAndContentContains(int projectId, String content, PageRequest pageable);

    @Query(value = "from Article a left join Project p on a.projectId=p.id where a.projectId=?1 and p.projectUse=1")
    List<Article> findJoinOn(int projectId, PageRequest pageable);

    @Query(value = "select * from article a where a.id<= :#{#article.id} and a.title like %:#{#article.title}% ", nativeQuery = true)
    List<Article> selectBySql(@Param("article") Article article, Pageable pageable);

}
